package com.springmvc;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

	@RequestMapping("/upload")
	public String upload(String desc,@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception{
		System.out.println("desc:"+desc);
		//FileOutputStream fos = new FileOutputStream(path+"/"+file.getOriginalFilename());
		//IOUtils.copy(file.getInputStream(), fos);
		//转存文件
		saveFile(file,request);
		return "redirect:/list";
	}
	public boolean saveFile(MultipartFile file,HttpServletRequest request){
		// 判断文件是否为空  
        if (!file.isEmpty()) {  
            try {  
                // 文件保存路径  
            	String path = request.getServletContext().getRealPath("/upload/")+file.getOriginalFilename();
                file.transferTo(new File(path));    // 转存文件  
                return true;  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return false;  
	}
	@RequestMapping("uploadMany")
	public String upload(@RequestParam("files") MultipartFile[] files,HttpServletRequest request){
		if(files != null && files.length>0){
			for(MultipartFile file : files){
				saveFile(file,request);
			}
		}
		return "redirect:/list";
	}
	@RequestMapping("list")
	public ModelAndView list(HttpServletRequest request){
		ModelAndView mav = new ModelAndView("success");
		String path = request.getServletContext().getRealPath("/upload");
		File uploadDest = new File(path);
		String [] fileNames = uploadDest.list();
		mav.addObject("files", fileNames);
		return mav;
	}
}
